/* eslint-disable */

// 题型

const questiontype = require("../../model/question/questiontype")
const question = require("../../model/question/question")


const { handleNumber, checkNull } = require("../../rules/verification")

// 根据id获取题型
exports.getById = async ({ id, pageNum, pageSize }) => {
    try {
        let res = await questiontype.findOne({
            offset: pageNum * pageSize - pageSize,
            limit: pageSize,
            where: { id },
            include: [{
                // model: question,
                where: { type_id: id },
                association: questiontype.hasMany(question, {
                    foreignKey: "type_id",
                    targetKey: "id"
                }),
            }]
        })
        if (res) {
            if (id == 1) {
                res.questions.forEach(item => {
                    item.options = JSON.parse(item.options)
                    item.answer = JSON.parse(item.answer)
                })
            }
            return { msg: "获取成功", code: "200", data: res }
        } else {
            return { msg: "获取失败", code: "400" }
        }
    } catch (err) { return { msg: "获取失败", code: "400", err } }
}

// 获取题型列表
exports.getList = async () => {
    // try {
        let res = await questiontype.findAll({
            'order': [
                ['id']
            ]
        })
        return { msg: "获取成功", code: "200", data: res }
    // } catch (err) { return { msg: "获取失败", code: "400", err } }
}

// 添加题型
exports.create = async ({ title }) => {
    try {
        let res = await questiontype.create({ title })
        if (res) return { msg: "添加成功", code: "200" }
        return { msg: "添加失败", code: "400" }
    } catch (err) { return { msg: "添加失败", code: "400", err } }
}

// 编辑题型
exports.edit = async ({ id, title }) => {
    try {
        let isTitle = await questiontype.findOne({ where: { title }, attributes: ["id"] })
        if (isTitle) {
            if (id !== isTitle.id) return { msg: "重复的题型名称", code: "400" }
        }
        let res = await questiontype.update({ title }, { where: { id } })
        if (res) return { msg: "编辑题型成功", code: "200" }
        return { msg: "编辑题型失败", code: "400" }
    } catch (err) { return { msg: "编辑题型失败", code: "400", err } }
}

// 删除题型
exports.remove = async ({ id }) => {
    try {
        let checkedId = checkNull(id, "id")
        if (checkedId.code !== "200") return checkedId
        let isRemove = await questiontype.findOne({ where: { id } })
        if (!isRemove) return { msg: "要删除的题型不存在", code: "400" }
        let res = await questiontype.destroy({ where: { id } })
        if (res) return { msg: "成功删除该题型", code: "200" }
        return { msg: "删除题型失败", code: "400" }
    } catch (err) { return { msg: "删除题型失败", code: "400", err } }
}

// answertab
// choicetab
// conpletiontab
// judgetab